/*
 * Copyright 2012 Andrea Parodi
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package eban.storebyrules.results;

import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

import java.util.Iterator;
import java.util.List;

/**
 * This class represent an implementation of Result
 * which allow to wrap results returned by a sqlite4java
 */
public class SqliteAdapter implements Result {
    private final SQLiteStatement resultSet;
    private final SQLiteConnection connection;

    public SqliteAdapter(SQLiteStatement resultSet, SQLiteConnection connection) {
        this.connection=connection;
        this.resultSet = resultSet;
    }
    private SQLiteStatement result() {
        return this.resultSet;
    }

    @Override public Iterator<Row> iterator() {
        return new RowIterator(this);
    }

    private class ResultsetColumns implements Columns {

        @Override public Column[] all() {
            try {
                List<Column> buff= Lists.newArrayList();
                for (int i=0;i< result().columnCount();i++){
                    buff.add(new DefaultColumn(i, result().getColumnName(i),SqliteAdapter.this));
                }

                Column[] ret = new Column[buff.size()];
                return buff.toArray(ret);
            }  catch (SQLiteException e) {
                throw new RuntimeException("cannot parse result columns",e);
            }
        }



        @Override public Column byName(String name) {
            try {

                SQLiteStatement result = result();
                for (int i=0;i<result.columnCount();i++){
                    if (result.getColumnName(i).equals(name))
                        return new DefaultColumn(i, name,SqliteAdapter.this);
                }
                throw new RuntimeException("field "+name+" not found");

            } catch (SQLiteException e) {
                throw new RuntimeException("cannot find given column.",e);
            }
        }

        @Override public Column at(int index) {
            try {

                return new DefaultColumn(index, result().getColumnName(index),SqliteAdapter.this);
            } catch (SQLiteException e) {
                throw new RuntimeException("cannot find given column.",e);
            }
        }

        @Override public int count() {
            try {
                return result().columnCount();
            } catch (SQLiteException e) {
                throw new RuntimeException("cannot find given column.",e);
            }
        }
    }

    private class ResultsetRow implements Row {

        @Override public Object get(Column column) {
            Preconditions.checkNotNull(resultSet);
            try {
                return resultSet.columnValue(column.getIndex());
            } catch (SQLiteException e) {
                throw new RuntimeException("cannot get value of cell for given column.",e);
            }
        }

        @Override public Result getResult() {
            return SqliteAdapter.this;
        }
    }

    private final ResultsetRow currentRow = new ResultsetRow();
    private final ResultsetColumns columns = new ResultsetColumns();

    @Override public void next() {
        try {
            resultSet.step();

        } catch (SQLiteException e) {
            throw new RuntimeException("cannot move to next row.",e);
        }
    }

    @Override public Columns columns() {
        return columns;
    }

    @Override public Row current() {
        return atEnd() ? Rows.NO_CURRENT_ROW : currentRow;
    }

    @Override public boolean atEnd() {

        return !resultSet.hasRow();

    }


    @Override public void close() {
        resultSet.dispose();
        //connection.dispose();

    }
}
